<!--
References:
  tutorials, image resize, kineticjs image class, save data url
	http://www.html5canvastutorials.com/
  image rotation
   http://jsfiddle.net/22Feh/5/
 -->

<!DOCTYPE html>
<html>
<head>
	<title>Image Manipulation</title>
	<style type = "text/css">
		#container{
			width: 800px;
			margin: auto;
		}
		#button,.message{
			position: relative;
			width: 800px;
			margin: auto;
		}
		.message{
			color: #808080;
			font-family: "Courier New" ;
		}
	</style>
</head>
<body>
		<div id = "button">
			<button id = "save">
				Save Image
			</button>
		</div>
		<p class = "message">Hold Shift then hover on element to rotate. Hold Ctrl then hover to resize</p>
	<div id = "container"></div>
	
	<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.4.min.js"></script>
	<script src="FileSaver.js"></script>
	<script src="canvas-toBlob.js"></script>
   <script defer="defer">
 
		function update(activeAnchor) {
        var group = activeAnchor.getParent();

        var topLeft = group.get('.topLeft')[0];
        var topRight = group.get('.topRight')[0];
        var bottomRight = group.get('.bottomRight')[0];
        var bottomLeft = group.get('.bottomLeft')[0];
        var image = group.get('.image')[0];

        var anchorX = activeAnchor.getX();
        var anchorY = activeAnchor.getY();

        // update anchor positions
        switch (activeAnchor.getName()) {
          case 'topLeft':
            topRight.setY(anchorY);
            bottomLeft.setX(anchorX);
            break;
          case 'topRight':
            topLeft.setY(anchorY);
            bottomRight.setX(anchorX);
            break;
          case 'bottomRight':
            bottomLeft.setY(anchorY);
            topRight.setX(anchorX); 
            break;
          case 'bottomLeft':
            bottomRight.setY(anchorY);
            topLeft.setX(anchorX); 
            break;
        }

        image.setPosition(topLeft.getPosition());

        var width = topRight.getX() - topLeft.getX();
        var height = bottomLeft.getY() - topLeft.getY();
        if(width && height) {
          image.setSize(width, height);
		  group.setOffset(width/2,height/2);
        }
      }
      function addAnchor(group, x, y, name) {
        var stage = group.getStage();
        var layer = group.getLayer();

        var anchor = new Kinetic.Circle({
          x: x,
          y: y,
          stroke: '#666',
          fill: '#ddd',
          strokeWidth: 2,
          radius: 8,
          name: name,
          draggable: true,
          dragOnTop: false,
		  visible: false
        });

        anchor.on('dragmove', function() {
          update(this);
          layer.draw();
        });
        anchor.on('mousedown touchstart', function() {
          group.setDraggable(false);
          this.moveToTop();
        });
        anchor.on('dragend', function() {
          group.setDraggable(true);
          layer.draw();
        });
        // add hover styling
        anchor.on('mouseover', function() {
          var layer = this.getLayer();
          document.body.style.cursor = 'pointer';
          this.setStrokeWidth(4);
          layer.draw();
        });
        anchor.on('mouseout', function() {
          var layer = this.getLayer();
          document.body.style.cursor = 'default';
          this.setStrokeWidth(2);
          layer.draw();
        });

        group.add(anchor);
      }
      function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
      }
		//custom image
		function drawCustom(layer){
			layer.draw();
		}
		//save image function
		function downloadImage(imageData){
			//Canvas2Image.saveAsPNG(canvas);
			window.location.href=imageData;
		}
		//get mouse coordinates based on the element IN the canvas
	    function getMousePos(canvas, evt) {
			var rect = canvas.getBoundingClientRect();
			return {
				x: evt.clientX - rect.left,
				y: evt.clientY - rect.top
			};
		}
		//rotate function
		function rotate(groupObj,canvas,mouseEvt,layer){
			//mouse current coordinates
			var mouseCoordinates = getMousePos(canvas,mouseEvt);
			var mX = mouseCoordinates.x;
			var mY = mouseCoordinates.y;
			//center of the group
			var centerX = (groupObj.getX()) + (groupObj.getWidth()/2);
			var centerY = (groupObj.getY()) + (groupObj.getHeight()/2);
			//theta
			var theta = Math.atan2(mY-centerY,mX-centerX);
			groupObj.setRotation(theta);
			layer.draw();
			console.log(mX +","+mY);
			console.log(centerX +","+centerY);
			
		}
	  /* blokblokblokblok
		initialize the stage
	  blokblokblokblok */
	  
      function initStage(images) {
		//declarations
			var currentElement;
			var shift = false;
			var control = false;
			var dilit = false;
			var tL;
			var tR;
			var bL;
			var bR;
			
			
		//kinetic variables
        var stage = new Kinetic.Stage({
          container: 'container',
          width: 981,
          height: 897
        });
		var canvas = stage.getContainer();
		var titanImg = new Kinetic.Image({
          x: 0,
          y: 0,
          image: images.titan,
          width: 800,
          height: 500,
          name: 'image',

        });

		var mustacheGroup = new Kinetic.Group({
          x: 100,
          y: 10,
          draggable: true,
		  width: 200,
          height: 10,
		  offset: [100,5],
		  name: 'group'
        });
        var eyebrowGroup = new Kinetic.Group({
          x: 100,
          y: 110,
          draggable: true,
		  width: 94,
          height: 104,
		   offset: [47,52],
		  name: 'group'
        });
        var layer = new Kinetic.Layer();
		var manongLayer = new Kinetic.Layer();
		  manongLayer.add(titanImg);
        layer.add(mustacheGroup);
        layer.add(eyebrowGroup);
		stage.add(manongLayer);
        stage.add(layer);

		
        var mustacheImg = new Kinetic.Image({
          x: 0,
          y: 0,
          image: images.mustache,
          width: 200,
          height: 10,
          name: 'image',
        });
		
        mustacheGroup.add(mustacheImg);
        addAnchor(mustacheGroup, 0, 0, 'topLeft');
        addAnchor(mustacheGroup, 200, 0, 'topRight');
        addAnchor(mustacheGroup, 200, 138, 'bottomRight');
        addAnchor(mustacheGroup, 0, 138, 'bottomLeft');

        mustacheGroup.on('dragstart', function() {
          this.moveToTop();
        });

        var eyebrowImg = new Kinetic.Image({
          x: 0,
          y: 0,
          image: images.eyebrow,
          width: 94,
          height: 104,
          name: 'image',
		 
        });

        eyebrowGroup.add(eyebrowImg);
        addAnchor(eyebrowGroup, 0, 0, 'topLeft');
        addAnchor(eyebrowGroup, 93, 0, 'topRight');
        addAnchor(eyebrowGroup, 93, 104, 'bottomRight');
        addAnchor(eyebrowGroup, 0, 104, 'bottomLeft');

        eyebrowGroup.on('dragstart', function() {
          this.moveToTop();
        });

        stage.draw();
		document.getElementById('save').addEventListener('click',function(){
			stage.toDataURL({
				callback: function(data){
					window.open(data,"manong.png")
				}
			});
			
			/* stage.toDataURL({
				callback: function(dataUrl){
					var data = dataUrl.replace("image/png", "image/octet-stream");
					downloadImage(data);
				}
			}); */
			
			 /* stage.toDataURL({
				callback: function(dataUrl){
					window.open(dataUrl);
				}
			}); */
	/* 		stage.toBlob({
				callback: function(blob){
					window.open(dataUrl);
				}
			}); */
		},false);
		//mouse moves on stage
		stage.on('mousemove',function(e){
			if(shift){
				rotate(currentElement,canvas,e,layer);
			}
			
		});
		
		//mouse over an element
		mustacheGroup.on('mouseover',function(){
			currentElement = this;
			tL = this.get('.topLeft')[0];
			tR = this.get('.topRight')[0];
			bR = this.get('.bottomRight')[0];
			bL = this.get('.bottomLeft')[0];
			if(control){
				tL.show();
				tR.show();
				bL.show();
				bR.show();
				layer.draw();
			}
		});
		eyebrowGroup.on('mouseover',function(){
			currentElement = this;
			tL = this.get('.topLeft')[0];
			tR = this.get('.topRight')[0];
			bR = this.get('.bottomRight')[0];
			bL = this.get('.bottomLeft')[0];
			if(control){
				tL.show();
				tR.show();
				bL.show();
				bR.show();
				layer.draw();
			}
		});
		
		//mouse out an element
		mustacheGroup.on('mouseout',function(){
			var tL = this.get('.topLeft')[0];
			var tR = this.get('.topRight')[0];
			var bR = this.get('.bottomRight')[0];
			var bL = this.get('.bottomLeft')[0];
			tL.hide();
			tR.hide();
			bL.hide();
			bR.hide();
			layer.draw();
		});
		eyebrowGroup.on('mouseout',function(){
			var tL = this.get('.topLeft')[0];
			var tR = this.get('.topRight')[0];
			var bR = this.get('.bottomRight')[0];
			var bL = this.get('.bottomLeft')[0];
			tL.hide();
			tR.hide();
			bL.hide();
			bR.hide();
			layer.draw();
		});
		//if a key is being pressed
		window.addEventListener('keydown',function(e){
			if(e.keyCode == "16"){
				shift = true;
			}else if(e.keyCode == "17"){
				control = true;
			}else if(e.keyCode == "192"){
				console.log('custom mode activate');
				customMode = true;
				layer.removeChildren();
				layer.draw();
			}else if(e.keyCode == "46"){
				dilit = true;
				currentElement.hide();
				layer.draw();
			}
			
		});
		/* 
		custom mode activation functions
		 */
		stage.on('mousedown',function(){
		
		});
		stage.on('mousedown',function(){
		
		});
		//if not
		window.addEventListener('keyup',function(e){
			if(e.keyCode == "16"){
				shift = false;
				currentElement = undefined;
			}else if(e.keyCode == "17"){
				control = false;
			}else if(e.keyCode == "46"){
				dilit = false;
			}
		});
      }
		

      var sources = {
        eyebrow: 'eyebrow.png',
        mustache: 'mustache.png',
		titan: 'manong.jpg'
      };
      loadImages(sources, initStage);
	
   </script>
</body>
</html>